package com.design.oop.control;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.ScrollView;

/**
 * @author 이재일
 */
public class CustomScrollView extends ScrollView {
	private OnScrollStartedListener onScrollStartedListener;
	private OnScrollChangedListener onScrollChangedListener;
	private OnScrollStoppedListener onScrollStoppedListener;
	private Runnable scrollerTask;
	private int initialPosition;
	private int checkTime = 100;
	private boolean touchScrollStarted;
	private boolean touchScrolling;

	public CustomScrollView(Context context, AttributeSet attributeset) {
		super(context, attributeset);
		scrollerTask = new Runnable() {
			public void run() {
				int newPosition = getScrollY();
				if (initialPosition - newPosition == 0) {
					touchScrollStarted = false;
					if (onScrollStoppedListener != null) {
						onScrollStoppedListener.onTouchScrollStopped();
					}
				} else {
					initialPosition = getScrollY();
					CustomScrollView.this.postDelayed(scrollerTask, checkTime);
				}
			}
		};
	}

	@Override
	protected void onScrollChanged(int left, int top, int oldLeft, int oldTop) {
		super.onScrollChanged(left, top, oldLeft, oldTop);
		if (touchScrolling && touchScrollStarted == false) {
			touchScrollStarted = true;
			if (onScrollStartedListener != null) {
				onScrollStartedListener.onTouchScrollStarted(left, top, oldLeft, oldTop);
			}
		}
		if (onScrollChangedListener != null) {
			onScrollChangedListener.onScrollChanged(this, left, top, oldLeft, oldTop);
		}
	}

	public void startScrollerTask() {
		initialPosition = getScrollY();
		this.postDelayed(scrollerTask, checkTime);
	}

	@Override
	public boolean onTouchEvent(MotionEvent ev) {
		switch (ev.getAction()) {
			case MotionEvent.ACTION_MOVE:
				touchScrolling = true;
				break;
			case MotionEvent.ACTION_UP:
				touchScrolling = false;
				this.startScrollerTask();
				break;
		}
		return super.onTouchEvent(ev);
	}

	public void setOnScrollStartedListener(OnScrollStartedListener onScrollStartedListener) {
		this.onScrollStartedListener = onScrollStartedListener;
	}

	public void setOnScrollChangedListener(OnScrollChangedListener customScrollViewListener) {
		this.onScrollChangedListener = customScrollViewListener;
	}

	public void setOnScrollStoppedListener(OnScrollStoppedListener onScrollStoppedListener) {
		this.onScrollStoppedListener = onScrollStoppedListener;
	}

	public static interface OnScrollStartedListener {
		public void onTouchScrollStarted(int left, int top, int oldLeft, int oldTop);
	}

	public static interface OnScrollChangedListener {
		public void onScrollChanged(CustomScrollView onScrollChangedListener, int left, int top, int oldLeft, int oldTop);
	}

	public static interface OnScrollStoppedListener {
		public void onTouchScrollStopped();
	}

}
